import { View } from "@tarojs/components";
import tabsStyleModule from "./index.module.scss";
import { useEffect, useState } from "react";
import { Search, Toast } from "@taroify/core";
import Taro from "@tarojs/taro";

interface TabsType {
  label: string;
  value: string;
}

interface TabsProps {
  type?: string;
  search?: (value: string) => void;
  tab?: (value: string) => void;
  isTab?: boolean;
}

export default function Tabs(props: TabsProps) {
  const tabsList: Array<TabsType> = [
    {
      label: "Products",
      value: "products",
    },
    {
      label: "Manufacturers",
      value: "manufacturers",
    },
  ];
  const [active, setActive] = useState<string>("products");
  const [value, setValue] = useState<string>("");
  const { isTab = true } = props;

  useEffect(() => {
    props.type && setActive(props.type);
  }, [props.type]);

  const handleSearch = () => {
    if (props.search) {
      props.search(value);
      return;
    }
    if (!value) {
      Toast.open({ type: "fail", message: "Please Input Keyword" });
      return;
    }
    setValue("");
    Taro.navigateTo({
      url: `/packages/searchPage/index?value=${value}&type=${active}`,
    });
  };

  const handleTab = (value: string) => {
    setActive(value);
    props.tab && props.tab(value);
  };

  return (
    <View>
      {isTab && (
        <View className={tabsStyleModule.tabs}>
          {tabsList.map((item) => (
            <View
              className={[
                tabsStyleModule.tabItem,
                item.value === active ? tabsStyleModule.active : "",
              ].join(" ")}
              key={item.value}
              onClick={() => handleTab(item.value)}
            >
              {item.label}
            </View>
          ))}
        </View>
      )}

      <View>
        <Search
          value={value}
          placeholder="Search"
          inputAlign="center"
          shape="rounded"
          className={tabsStyleModule.search}
          onChange={(e) => setValue(e.detail.value)}
          onSearch={() => handleSearch()}
        ></Search>
      </View>
    </View>
  );
}
